package com.ebt.m.customer.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.listview.pulltorefresh.PullToRefreshView;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.PrefKit;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerContact;
import com.ebt.m.customer.entity.CustomerDetail;
import com.ebt.m.customer.event.EventCustomerListRefresh;
import com.ebt.m.customer.fragment.BaseLazySwipeRefreshFragment;
import com.ebt.m.customer.net.json.CustomerDetailJson;
import com.ebt.m.customer.util.PhoneUtil;
import com.ebt.m.customer.view.CustomerInfoUnitEditTextForProfile;
import com.ebt.m.customer.view.CustomerInfoUnitEditTextForProfile4Address;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.utils.DateUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.EBTProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.ebt.m.receiver.PhoneStateReceiver.CALLING_FLAG;


/**
 * 客户详情-基本信息
 */
public class FragmentCustomerProfile extends BaseLazySwipeRefreshFragment {

    private EBTProgress progress;

    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_phone;//电话
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_email;//邮箱
    private CustomerInfoUnitEditTextForProfile4Address fragment_customer_detail_info_unit_address;//地址
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_creditcard;//身份证
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_age;//年龄
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_birthday;//生日
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_degree;//学历
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_level;//等级
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_sex;//性别
    private CustomerInfoUnitEditTextForProfile fragment_customer_detail_info_unit_marriage;//婚姻

    //values
    private Bundle mGetBundle;
    private CustomerDetail mCustomerDetail;
    private String mCustomerUuid;

    private View noNetContainer;
    private View netSlowContainer;
    private View content_view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initArgs();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_customer_profile;
    }

    @Override
//    protected void onSwipeRefresh(SwipeRefreshLayout swipeRefreshLayout) {
    protected void onSwipeRefresh(PullToRefreshView swipeRefreshLayout) {
        refresh();
    }

    @Override
    protected void onCreateContentView(View contentView, Bundle savedInstanceState) {
        content_view = contentView.findViewById(R.id.content_view);
        progress = (EBTProgress) contentView.findViewById(R.id.progress);
        noNetContainer = contentView.findViewById(R.id.no_net_container);
        netSlowContainer = contentView.findViewById(R.id.net_slow_container);
        noNetContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refresh();
            }
        });
        netSlowContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refresh();
            }
        });
        fragment_customer_detail_info_unit_phone = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_phone);
        fragment_customer_detail_info_unit_email = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_email);
        fragment_customer_detail_info_unit_address = (CustomerInfoUnitEditTextForProfile4Address) contentView.findViewById(R.id.fragment_customer_detail_info_unit_address);
        fragment_customer_detail_info_unit_creditcard = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_creditcard);
        fragment_customer_detail_info_unit_age = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_age);
        fragment_customer_detail_info_unit_birthday = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_birthday);
        fragment_customer_detail_info_unit_degree = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_degree);
        fragment_customer_detail_info_unit_level = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_level);
        fragment_customer_detail_info_unit_sex = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_sex);
        fragment_customer_detail_info_unit_marriage = (CustomerInfoUnitEditTextForProfile) contentView.findViewById(R.id.fragment_customer_detail_info_unit_marriage);
    }

    @Override
    public void onFirstUserVisible() {
        super.onFirstUserVisible();
        getView().postDelayed(new Runnable() {
            @Override
            public void run() {
                showProgress();
                refresh();
            }
        }, CustomerConstant.Delay.FRAGMENT_UPDATE_DELAY);
    }

    /**
     * 空图和错误图片显示逻辑
     *
     * @param empty
     * @param no_net
     * @param net_slow
     */
    public void showEmpty(boolean empty, boolean no_net, boolean net_slow) {
//        content_view.setVisibility(empty ? View.GONE : View.VISIBLE);
        noNetContainer.setVisibility(no_net ? View.VISIBLE : View.GONE);
        netSlowContainer.setVisibility(net_slow ? View.VISIBLE : View.GONE);
    }

    private void showProgress() {
        if (progress != null) {
            progress.setVisibility(View.VISIBLE);
        }
    }

    private void hideProgress() {
        if (progress != null) {
            progress.setVisibility(View.GONE);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initArgs() {
        mGetBundle = getArguments();
        if (mGetBundle != null) {
            mCustomerDetail = (CustomerDetail) mGetBundle.getSerializable(CustomerConstant.CUSTOMER_DETAIL_ENTITY);
            mCustomerUuid = mGetBundle.getString(CustomerConstant.CUSTOMER_UUID);
        }
    }

    private void refresh() {
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.getCustomerDetail(mCustomerUuid).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerDetailSubscriber());
    }

    private Observer<CustomerDetailJson> getCustomerDetailSubscriber() {
        return new Observer<CustomerDetailJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                if (isAdded()) {
                    UIHelper.makeToast(getContext(), getContext().getString(R.string.network_fail));
                }
                if (NetUtils.isNetworkAvailable(getContext())) {
                    showEmpty(true, false, true);
                } else {
                    showEmpty(true, true, false);
                }
                hideRefresh();
                hideProgress();
            }

            @Override
            public void onNext(CustomerDetailJson customerDetailJson) {
                if (customerDetailJson == null || customerDetailJson.error != null || customerDetailJson.data == null) {
                    UIHelper.makeToast(getContext(), getString(R.string.network_fail));
                    showEmpty(true, false, true);
                } else {
                    mCustomerDetail = customerDetailJson.data;
                    initValues();
                    showEmpty(false, false, false);
                }
                hideRefresh();
                hideProgress();
            }
        };
    }

    public void initValues() {
        if (mCustomerDetail != null) {
            //电话
            fragment_customer_detail_info_unit_phone.setEditTextText(getCustomerContact(mCustomerDetail, CustomerConstant.CustomerContact.TYPE_PHONE));
            fragment_customer_detail_info_unit_phone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!TextUtils.isEmpty(fragment_customer_detail_info_unit_phone.getEditTextText().toString())) {
                        PrefKit.writeString(getContext(), CALLING_FLAG, mCustomerUuid);
                        // TODO 修复点击打电话功能的同时打开笔记页面的业务逻辑
//                        Intent intent = new Intent(getContext(), ActivityCustomerNote.class);
//                        intent.putExtra(CustomerConstant.CustomerNote.MODE, CustomerConstant.CustomerNote.MODE_ADD);
//                        intent.putExtra(CustomerConstant.CUSTOMER_UUID, mCustomerUuid);
//                        intent.putExtra(CustomerConstant.CUSTOMER_DETAIL_NOTE_DEFAULT_VALUE, "客户较有意向，准备近期面谈详聊");
//                        getContext().startActivity(intent);
//                        ((Activity) getContext()).overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                        //弹出打电话弹出窗
                        PhoneUtil.callPhone(getActivity(), fragment_customer_detail_info_unit_phone.getEditTextText().toString());
                    }
                }
            });
            //邮箱
            fragment_customer_detail_info_unit_email.setEditTextText(getCustomerContact(mCustomerDetail, CustomerConstant.CustomerContact.TYPE_EMAIL));
            //地址
            fragment_customer_detail_info_unit_address.setEditTextText(getCustomerAddress(mCustomerDetail));
            //年龄
            fragment_customer_detail_info_unit_age.setEditTextText(getCustomerAge(mCustomerDetail));
            fragment_customer_detail_info_unit_creditcard.setEditTextText(getCustomerCreditcard(mCustomerDetail));
            //生日
            fragment_customer_detail_info_unit_birthday.setEditTextText(getCustomerBirthday(mCustomerDetail));
            //学历
            fragment_customer_detail_info_unit_degree.setEditTextText(getCustomerEducationGrading(mCustomerDetail));
            //等级
            fragment_customer_detail_info_unit_level.setEditTextText(getCustomerCareerCategory(mCustomerDetail));
            //性别
            fragment_customer_detail_info_unit_sex.setEditTextText(getCustomerSex(mCustomerDetail));
            //婚姻
            fragment_customer_detail_info_unit_marriage.setEditTextText(getCustomerMarriage(mCustomerDetail));
        }
    }

    private String getCustomerContact(CustomerDetail customerDetail, int type) {
        if (customerDetail == null) {
            return null;
        }

        List<CustomerContact> contacts = customerDetail.getListCustomerContact();
        if (contacts == null || contacts.size() == 0) {
            return null;
        }
        for (CustomerContact item : contacts) {
            if (item.ctype != null && type == item.ctype) {
                return item.cvalue;
            }
        }
        return null;
    }

    private String getCustomerAddress(CustomerDetail customerDetail) {
        if (customerDetail == null
                || customerDetail.getListCustomerAddress() == null
                || customerDetail.getListCustomerAddress().size() == 0) {
            return null;
        }

        return customerDetail.getListCustomerAddress().get(0).details;
    }

    private String getCustomerAge(CustomerDetail customerDetail) {
//        if (getCustomerIsConfirm(customerDetail)) {
        return String.valueOf(DateUtils.getAge(getDateBySecond(customerDetail)));
//        }else{
//            return "";
//        }
    }

    private String getCustomerCreditcard(CustomerDetail customerDetail) {
        return customerDetail.getIdCard();

    }

    private Date getDateBySecond(CustomerDetail customerDetail) {
        if (customerDetail == null || customerDetail.getBirthday() == null) {
            return DateUtils.getDefaultBirthdayDate();
        }
        return DateUtils.parseTimestampInSecondToDate(customerDetail.getBirthday());
    }

    private String getCustomerBirthday(CustomerDetail customerDetail) {
        if (getCustomerIsConfirm(customerDetail)) {
            return DateUtils.getBirthday(getDateBySecond(customerDetail));
        }
        return "";
    }

    private boolean getCustomerIsConfirm(CustomerDetail customerDetail) {
        if (customerDetail == null) {
            return false;
        }
        if (customerDetail.getIsConfirm() == null || customerDetail.getIsConfirm() == 0) {
            return false;
        }
        return true;
    }

    private String getCustomerEducationGrading(CustomerDetail customerDetail) {
        if (customerDetail == null) {
            return CustomerConstant.EducationGrade.getShowText(null);
        }
        return CustomerConstant.EducationGrade.getShowText(customerDetail.getEducationGrading());
    }

    private String getCustomerCareerCategory(CustomerDetail customerDetail) {
        if (customerDetail == null) {
            return CustomerConstant.CareerCategory.getShowText(null);
        }
        return CustomerConstant.CareerCategory.getShowText(customerDetail.getCareerCategory());
    }

    private String getCustomerSex(CustomerDetail customerDetail) {
        String ret;
        if (customerDetail == null) {
            ret = CustomerConstant.Profile.SEX_WOMAN;
        } else if (customerDetail.getSex() == null || customerDetail.getSex() == 0) {
            ret = CustomerConstant.Profile.SEX_WOMAN;
        } else {
            ret = CustomerConstant.Profile.SEX_MAN;
        }
        return ret;
    }

    private String getCustomerMarriage(CustomerDetail customerDetail) {
        String ret;
        if (customerDetail == null) {
            ret = CustomerConstant.Profile.MARRIAGE_NO;
        } else if (customerDetail.getMarriage() != null && customerDetail.getMarriage() != 0) {
            ret = CustomerConstant.Profile.MARRIAGE_YES;
        } else {
            ret = CustomerConstant.Profile.MARRIAGE_NO;
        }
        return ret;
    }

    public static FragmentCustomerProfile newInstance(CustomerDetail customerDetail, String mode, String uuid, boolean hideAvatar, boolean editable) {
        Bundle bundle = new Bundle();
        if (customerDetail != null) {
            bundle.putSerializable(CustomerConstant.CUSTOMER_DETAIL_ENTITY, customerDetail);
        }
        bundle.putString(CustomerConstant.CUSTOMER_DETAIL_MODE, mode);
        bundle.putString(CustomerConstant.CUSTOMER_UUID, uuid);
        FragmentCustomerProfile fragmentCustomerDetail = new FragmentCustomerProfile();
        fragmentCustomerDetail.setArguments(bundle);
        return fragmentCustomerDetail;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCustomerListRefresh event) {
        refresh();
    }

    public CustomerDetail getCustomerDetail() {
        return mCustomerDetail;
    }
}